<template>
  <el-dialog
    :model-value="dialogModify"
    width="40%"
    title="设施详情-编辑"
    :before-close="handleClose"
  >
    <el-divider />
    <!-- 添加表单内容 -->
    <el-form :model="form" ref="formRef" :rules="rules" label-width="120px">
      <el-form-item label="设施名称：" prop="name">
        <el-input v-model="form.name" placeholder="请输入设施名称" />
      </el-form-item>

      <el-form-item label="封面图片：" prop="coverUrl">
        <el-upload
          class="upload-box"
          action="#"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleCoverChange"
          :on-remove="handleCoverRemove"
          accept="image/jpeg,image/png,image/gif,image/jpg"
        >
          <template v-if="form.coverUrl">
            <img :src="form.coverUrl" class="preview-image" />
            <div class="delete-icon" @click.stop="handleCoverRemove">
              <el-icon><Delete /></el-icon>
            </div>
          </template>
          <div v-else class="upload-placeholder">
            <el-icon><Plus /></el-icon>
            <span>点击上传</span>
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item label="视频URL：" prop="videoId">
        <el-select v-model="form.videoId" placeholder="请选择">
          <el-option
            v-for="item in videoListAll"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="设施介绍：" prop="intro">
        <WangEditor
          v-model="form.intro"
          height="200"
          @change="handleEditorChange"
        />
      </el-form-item>

      <el-form-item label="发布状态：" prop="releaseStatus">
        <el-select v-model="form.releaseStatus" placeholder="请选择">
          <el-option label="草稿" :value="0" />
          <el-option label="已发布" :value="1" />
        </el-select>
      </el-form-item>

      <el-form-item label="空间名称：" prop="spaceIdList">
        <el-select v-model="form.spaceIdList" placeholder="请选择" multiple>
          <el-option
            v-for="item in spaceListAll"
            :key="item.spaceId"
            :label="item.name"
            :value="item.spaceId"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup name="ModifyFacilityDialog">
import { ref, watch } from 'vue';
import { uploadPic } from '@/api/Upload/upload';
import { ElMessage } from 'element-plus';
import { Plus, Delete } from '@element-plus/icons-vue';
import WangEditor from '@/components/WangEditor/index.vue';
import {
  getFacilityDetails,
  modifyFacility,
  getSpaceList,
} from '@/api/Venue/facility';
import { getVideoList } from '@/api/Venue/space';

const props = defineProps({
  dialogModify: {
    type: Boolean,
  },
  ModifyId: {
    type: String,
    default: '',
  },
});

// 初始化表单数据
const initialForm = {
  name: '',
  coverUrl: '',
  videoId: '',
  releaseStatus: '',
  intro: '',
  spaceIdList: [],
};

const form = ref({ ...initialForm });
const formRef = ref(null);
const videoListAll = ref([]);
const spaceListAll = ref([]);
const loading = ref(false);
const spaceVOList = ref([]);

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入设施名称', trigger: 'blur' }],
  coverUrl: [{ required: true, message: '请上传封面图片', trigger: 'change' }],
  intro: [
    { required: true, message: '请输入设施介绍', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value || value.trim() === '<p><br></p>') {
          callback(new Error('请输入设施介绍'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
  releaseStatus: [
    { required: true, message: '请选择发布状态', trigger: 'change' },
  ],
};

// 获取详情数据
const getFacilityData = async (id) => {
  loading.value = true;
  try {
    const res = await getFacilityDetails(id);
    if (res.data.code === 200) {
      const details = res.data.data;
      const spaceVOList =
        details.spaceVOList?.map((item) => item.spaceId) || [];
      console.log('spaceVOList', spaceVOList);

      form.value = {
        name: details.name,
        coverUrl: details.coverUrl,
        videoId: details.media?.title || null,
        releaseStatus: details.releaseStatus,
        intro: details.intro,
        spaceIdList: spaceVOList,
      };
    }
  } catch (error) {
    console.error('获取详情失败:', error);
  } finally {
    loading.value = false;
  }
};

// 获取下拉选项数据
const getOptions = async () => {
  try {
    // 获取视频列表
    const videoRes = await getVideoList();
    if (videoRes.data.code === 200) {
      videoListAll.value = videoRes.data.data || [];
    }

    // 获取空间列表
    const spaceRes = await getSpaceList();
    if (spaceRes.data.code === 200) {
      spaceListAll.value = spaceRes.data.data || [];
    }
  } catch (error) {
    console.error('获取选项数据失败:', error);
  }
};

// 监听对话框和行数据变化
watch(
  [() => props.dialogModify, () => props.ModifyId],
  ([newDialog, newId]) => {
    if (newDialog && newId) {
      getOptions();
      getFacilityData(newId);
    }
  }
);

// 添加图片格式校验函数
const validateImageType = (file) => {
  const acceptedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'];
  if (!acceptedTypes.includes(file.type)) {
    ElMessage.error('只能上传 JPG/PNG/GIF 格式的图片！');
    return false;
  }
  return true;
};

// 修改封面图片上传处理
const handleCoverChange = async (file) => {
  if (!validateImageType(file.raw)) {
    return;
  }

  const formData = new FormData();
  formData.append('picture', file.raw);
  try {
    const response = await uploadPic(formData);
    if (response.data.code === 200) {
      form.value.coverUrl = response.data.data.url;
      ElMessage.success('上传成功');
      await formRef.value?.validateField('coverUrl');
    } else {
      ElMessage.error(response.data.msg || '上传失败');
    }
  } catch (error) {
    console.error('上传失败:', error);
    ElMessage.error('上传失败');
  }
};

// 处理封面图片移除
const handleCoverRemove = () => {
  form.value.coverUrl = '';
};

// 处理编辑器内容变化
const handleEditorChange = (html) => {
  form.value.intro = html;
  formRef.value?.validateField('intro');
};

const emit = defineEmits(['confirm', 'cancel']);

// 处理取消
const handleCancel = () => {
  form.value = { ...initialForm };
  if (formRef.value) {
    formRef.value.resetFields();
  }
  emit('cancel');
};

// 处理确认
const handleConfirm = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = {
          ...form.value,
          facilityId: props.ModifyId,
        };
        const res = await modifyFacility(submitData);
        if (res.data.code === 200) {
          ElMessage.success('修改成功');
          emit('confirm');
          handleCancel();
        } else {
          ElMessage.error(res.data.msg || '修改失败');
        }
      } catch (error) {
        console.error('保存失败:', error);
        ElMessage.error('保存失败');
      }
    } else {
      ElMessage.warning('请填写完整信息');
      return false;
    }
  });
};

// 关闭对话框
const handleClose = () => {
  handleCancel();
};
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.upload-box {
  width: 120px;
  height: 120px;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  &:hover {
    border-color: #409eff;
  }

  .preview-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
    position: absolute;
    top: 0;
    left: 0;
  }

  .upload-placeholder {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
    color: #8c8c8c;

    .el-icon {
      font-size: 20px;
      margin-bottom: 8px;
    }

    span {
      display: block;
      font-size: 12px;
    }
  }

  .delete-icon {
    position: absolute;
    top: 0;
    right: 0;
    width: 24px;
    height: 24px;
    background-color: rgba(0, 0, 0, 0.5);
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    opacity: 0;
    transition: opacity 0.3s;
    border-bottom-left-radius: 8px;

    &:hover {
      background-color: rgba(0, 0, 0, 0.7);
    }
  }

  &:hover .delete-icon {
    opacity: 1;
  }
}

:deep(.editor-container) {
  margin-bottom: 20px;
}
</style>
